/**
 *
 * Copyright 2016-present authing
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React from 'react';
import { connect } from 'react-redux';
import CodePush from 'react-native-code-push';
import { bindActionCreators } from 'redux';
import { Text, TouchableOpacity, StyleSheet } from 'react-native';

import { createIconSetFromIcoMoon } from 'react-native-vector-icons';
import icoMoonConfig from '../config/icoMoonConfig.json';
const Icon = createIconSetFromIcoMoon(icoMoonConfig);

import Main from '../pages/MainPage/Main';
import * as authCreators from '../actions/auth';
import * as teamCreators from '../actions/team';
import SCRMWebViewPage from '../pages/ItemDetail/SCRMWebViewPage';
import { HOME_ROUTE } from '../constants/VueRoutes';
import { IS_DEBUG } from '../constants/Runtime';
const backImage = require("../img/arrow_left.png");

class SCRMWebContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      article: { url: ''},
      isVisible: true
    }

    this.handled = false;
    this.beforeNavigate = this.beforeNavigate.bind(this);
    this.backFromScreen = this.backFromScreen.bind(this);
  }

  static navigationOptions = ({ navigation }) => {
    const {state} = navigation;
    let title = state.routeName === 'Main' ? '工作台' : '载入中...';
    if (state.params && state.params.article && state.params.article.title) {
      title = `${state.params.article.title}`;
    }

    if (state.params && state.params.title) {
      title = `${state.params.title}`;
    }
    
    return {
      title: title,
      tabBarIcon: ({ tintColor }) => (
        <Icon name="workbench_n" size={24} color={tintColor} />
      ),
      headerRight:
      (
        <TouchableOpacity 
          style={styles.refreshStyle}
          onPress={() => {
            navigation.state.params.handleRefresh && navigation.state.params.handleRefresh();
        }}>
          <Text
          style={styles.refreshTextStyle}
          >刷新</Text>
        </TouchableOpacity>
      ),
      // headerBackImage: backImage
    };
  };

  backFromScreen (previousState) {
    if (IS_DEBUG) {
      let { params } = this.props.navigation.state;
      this.setState(Object.assign(previousState || {}, {
        isVisible: true
      }));
    }
  }

  beforeNavigate () {
    if (IS_DEBUG) {
      let { params } = this.props.navigation.state;
      const freshParams = { 
        previousState: { article: params.article },
        backFromScreen: this.backFromScreen,
      };
      this.props.navigation.setParams(freshParams);
      requestAnimationFrame(() => this.setState({
        isVisible: false
      }))
      return freshParams;
    }
  }

  componentDidMount() {
    if (IS_DEBUG) {
      this.props.navigation.setParams({ 
        beforeNavigate: this.beforeNavigate, 
      });
    }

    let { params } = this.props.navigation.state; 
    if (!params || !params.article) {
      this.initParams();
    }
  }

  componentWillUnmount() {
    let { params } = this.props.navigation.state;
    if (IS_DEBUG) {
      if (!this.handled && params && params.histories) {
        const history = params.histories.pop();
        history.backFromScreen(history.previousState);
        this.handled = true;
      }
    }
  }

  async initParams () {
    let homeLink = await HOME_ROUTE();
    this.setState({
      article: {
        "url": homeLink,
        "title": "工作台",
      }
    })
  }


  render() {
    let props = Object.assign({}, (this.props || {}), this.state);
    if (!this.state.isVisible) return (
      <View />
    );

    return <SCRMWebViewPage {...props} />;
  }
}

const mapStateToProps = (state) => {
  const { auth, team } = state;
  return {
    auth,
    team
  };
};

const mapDispatchToProps = (dispatch) => {
  const authActions = bindActionCreators(authCreators, dispatch);
  const teamActions = bindActionCreators(teamCreators, dispatch); // test code

  return {
    authActions,
    teamActions // test code
  };
};


const styles = StyleSheet.create({
  refreshStyle: {
    padding: 4
  },
  refreshTextStyle: {
    marginRight: 4,
    color: 'white',
    fontSize: 16
  }
});

export default connect(mapStateToProps, mapDispatchToProps)(SCRMWebContainer);
